using System;
using System.Linq;
using MvcSoft1Demo.Models;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;

namespace MvcSoft1Demo.Repository
{
    public class EfRepository<T> : IRepository<T> where T : BaseEntity
    {
        private readonly MvcSoft1Demo.Db.Soft1DemoDb _db;

        private readonly DbSet<T> _table;

        public EfRepository()
        {
            _db = new Db.Soft1DemoDb();
            _table = _db.Set<T>();
        }


        public T GetById(int id)
        {
            var entity = _table.Where(x => x.Id == id).FirstOrDefault();
            return entity;
        }

        public IQueryable<T> Table
        {
            get
            {
                return _table.AsQueryable();
            }
        }

        public void Insert(T entity)
        {
            entity.IsActvied = true;
            entity.IsDeleted = false;
            entity.CreatedTime = DateTime.Now;
            entity.UpdatedTime = DateTime.Now;
            entity.DisplayOrder = 0;
            entity.CreatorId = 0;
            _table.Add(entity);
            _db.SaveChanges();
        }
        public void Update(T entity)
        {
            entity.UpdatedTime = DateTime.Now;
            _table.Update(entity);
            _db.SaveChanges();
        }
        public void Delete(int id)
        {
            var entity = GetById(id);

            if (entity != null)
            {
                entity.IsDeleted=true;
                Update(entity);
            }
        }
    }
}